﻿Imports MongoDB.Bson
Imports MongoDB.Driver
Imports MongoDB.Driver.Builders

Public Class DBHelper

    Public Shared Function SetupServer() As MongoServer

        Dim msServer As MongoServer = Nothing
        Dim mssSettings As MongoServerSettings = Nothing

        Try

            mssSettings = New MongoServerSettings
            mssSettings.Server = New MongoServerAddress(ConfigurationManager.AppSettings("DatabaseServerAddress"), _
                                                        ConfigurationManager.AppSettings("DatabaseServerPort"))
            mssSettings.DefaultCredentials = New MongoCredentials(ConfigurationManager.AppSettings("DatabaseUser"), _
                                                                  ConfigurationManager.AppSettings("DatabasePassword"))
            msServer = New MongoServer(mssSettings)

        Catch ex As Exception

        Finally

            SetupServer = msServer

            msServer = Nothing
            mssSettings = Nothing

        End Try

    End Function

    Public Shared Function GetDataBase() As MongoDatabase

        Dim msServer As MongoServer = Nothing
        Dim mdDatabase As MongoDatabase = Nothing

        Try

            msServer = SetupServer()
            mdDatabase = msServer(ConfigurationManager.AppSettings("DatabaseName"))

        Catch ex As Exception

        Finally

            GetDataBase = mdDatabase

            msServer = Nothing
            mdDatabase = Nothing

        End Try

    End Function

    'Return Trebuchet User
    Public Shared Function GetUserByID(ByVal UserID As ObjectId) As Trebuchet.User

        Dim mdDatabase As MongoDatabase = Nothing
        Dim mcUsers As MongoCollection(Of Trebuchet.User) = Nothing
        Dim mcUserCursor As MongoCursor = Nothing

        mdDatabase = DBHelper.GetDataBase()
        mcUsers = mdDatabase.GetCollection(Of Trebuchet.User)("Users")

        mcUserCursor = mcUsers.FindAs(Of Trebuchet.User)(Query.And(Query.EQ("_id", UserID), Query.EQ("Active", True)))

        If Not mcUserCursor Is Nothing _
                AndAlso mcUserCursor.Count > 0 Then

            Return mcUserCursor(0)

        End If

    End Function

End Class
